package com.example.yuntiku.Servlet;

import com.example.yuntiku.dao.impl.TeacherDao;
import com.example.yuntiku.dao.impl.UsersDao;
import com.example.yuntiku.entity.Teacher;
import com.example.yuntiku.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "UsersServlet", value = "/UsersServlet")
public class UsersServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获得用户名和密码
        request.setCharacterEncoding("utf-8");
        String email = request.getParameter("email");
        String upwd = request.getParameter("upwd");
        String role = request.getParameter("role"); // 获取用户选择的身份
        if ("student".equals(role)) {
            // 学生登录
            UsersDao usersDao = new UsersDao();
            User user = usersDao.selectUsers(email, upwd);
            if (user != null) {
                // 将登录信息放入session中
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                // 登录成功后重定向到学生主页
                response.sendRedirect("CurriculumServlet");
            } else {
                // 登录失败，回到登录页面
                request.getRequestDispatcher("logon.jsp").forward(request, response);
            }
        } else if ("teacher".equals(role)) {
            // 教师登录
            TeacherDao teacherDao = new TeacherDao();
            Teacher user = teacherDao.selectUsers(email, upwd);
            if (user != null) {
                // 将登录信息放入session中
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                // 登录成功后重定向到教师主页
                response.sendRedirect("IndexServlet");
            } else {
                // 登录失败，回到登录页面
                request.getRequestDispatcher("logon.jsp").forward(request, response);
            }
        } else {
            // 其他未知身份，处理逻辑（可以根据实际情况添加）
            response.sendRedirect("logon.jsp");
        }
    }
}